package org.chispa.api.util;

import org.chispa.api.domain.DomainParameter;
import org.json.JSONException;
import org.json.JSONObject;

public class JSONManager {
	
	private JSONManager(){};
	
	private static final String REQ="request";
	private static final String UUID="uuid";
	private static final String NS="ns";
	private static final String PARAM="param";
	private static final String DOMAIN="domain";
	private static final String LOW="low";
	private static final String HIGH="high";
	private static final String BIN="bin";
	
	public static class ParamHelper{
		
		private String uuid;
		private String ns;
		private String param;
		
		public ParamHelper(String uuid,String ns,String param)
		{
			this.uuid=uuid;
			this.ns=ns;
			this.param=param;
		}

		public String getUuid() {
			return uuid;
		}

		public String getNs() {
			return ns;
		}

		public String getParam() {
			return param;
		}
	}

	public static JSONObject paramsToJSON(String uuid, String ns, String param) throws JSONException
	{
		if(ns.endsWith("\\"))
			ns=ns.substring(0, ns.length()-1);
		String jsonStr="{\""+REQ+"\": {\""+UUID+"\": "+uuid+", \""+NS+"\": "+ExpressionLanguage.quote(ns)+", \""+PARAM+"\" : "+param+"}}";
		return new JSONObject(jsonStr);
	}
	
	public static ParamHelper JSONtoParam(JSONObject obj) throws JSONException
	{
		JSONObject reqParams=obj.getJSONObject(REQ);
		String uuid=reqParams.getString(UUID);
		String ns=reqParams.getString(NS);
		String param=reqParams.getString(PARAM);
		return new ParamHelper(uuid,ns,param);
	}
	
	public static JSONObject domainToJSON(DomainParameter dom) throws JSONException
	{
		String bin=dom.getBinNumEnc();
		String low=dom.getLowerEnc();
		String high=dom.getUpperEnc();
		String uuid=dom.getUuid();
		String ns=dom.getNs();
		String name=dom.getName();
		String jsonStr="{\""+DOMAIN+"\": {\""+LOW+"\": "+low+", \""+HIGH+"\": "+high+", \""+UUID+"\": " +
				""+uuid+",\""+PARAM+"\": "+name+",\""+NS+"\": "+ExpressionLanguage.quote(ns)+", \""+BIN+"\" : "+bin+"}}";;
		return new JSONObject(jsonStr);
	}
	
	public static DomainParameter JSONtoDomain(JSONObject obj) throws JSONException
	{
		JSONObject dom=obj.getJSONObject(DOMAIN);
		DomainParameter toRet=new DomainParameter();
		toRet.setBinNumEnc(dom.getString(BIN));
		toRet.setLowerEnc(dom.getString(LOW));
		toRet.setUpperEnc(dom.getString(HIGH));
		toRet.setUuid(dom.getString(UUID));
		toRet.setNs(dom.getString(NS));
		toRet.setName(dom.getString(PARAM));
		return toRet;
	}

}
